// web/src/app/learn/(course)/courses/[courseId]/_components/course-sidebar.tsx
import React from 'react';
import {Chapter, Course, UserProgress} from "@prisma/client";
import {currentUser} from "@/lib/auth";
import {redirect} from "next/navigation";
import {db} from "@/lib/db";
import CourseSidebarItem from "@/app/learn/(course)/courses/[courseId]/_components/course-sidebar-item";
import CourseProgress from "@/components/learn/course-progress";

interface Props {
    course: Course & {
        chapters: (Chapter & {
            userProgress: UserProgress[] | null
        })[]
    }
    progressCount: number
}

const CourseSidebar = async ({course, progressCount}: Props) => {
    const user = await currentUser()
    if (!user) return redirect('/learn')

    const purchase = await db.purchase.findUnique({
        where: {
            // @ts-ignore
            // @@unique
            userId_courseId: {
                userId: user.id!,
                courseId: course?.id
            }
        }
    })

    return (
        <div className={`h-full border-r flex flex-col overflow-y-auto shadow-sm`}>
            <div className={`p-8 flex flex-col border-b`}>
                <h1 className={`font-semibold`}>
                    {course.title}
                </h1>
                {purchase && (
                    <div className={`mt-10`}>
                        <CourseProgress
                            variant={'success'}
                            value={progressCount}
                        />
                    </div>
                )}
            </div>
            <div className={`flex flex-col w-full`}>
                {course.chapters.map((chapter) => (
                    <CourseSidebarItem
                        key={chapter.id}
                        id={chapter.id}
                        label={chapter.title}
                        isCompleted={!!chapter.userProgress?.[0]?.isCompleted}
                        courseId={course.id}
                        isLocked={!chapter.isFree && !purchase}
                    />
                ))}
            </div>
        </div>
    );
};

export default CourseSidebar;